<?php

namespace Zms\Sms\Drive;

use Zms\Sms\Drive\Config\Ztconfig;
use Zms\Sms\SmsResult;
use Zms\Request\Http;
use Zms\Unit\Json;
use Zms\Unit\Str;

/**
 * 助通科技短信
 * @link https://doc.zthysms.com/web/#/1/7
 */
class Ztsms extends SmsBasics
{
    const SEND_SMS_API = '/v2/sendSms';//发送任意短信api

    const SEND_SMS_TMP_API = '/v2/sendSmsTp';//发送模板短信api

    const BALANCE_API = '/v2/balance';//获取短信余额api


    /**
     * 获取短信配置
     * @return Ztconfig
     */
    protected function getConfig(): Ztconfig
    {
        return parent::getConfig(); // TODO: Change the autogenerated stub
    }


    public function getBalance(): int
    {
        $conf = $this->getConfig();
        $tKey = time();
        $data = [
            'username' => $conf->username,
            'password' => md5(md5($conf->password) . $tKey),
            'tKey' => $tKey
        ];
        $body = Http::instance()->setMethod('POST')->setData(Json::encode($data))->setHeader('Content-Type', 'application/json; charset=utf-8')->execute($conf->host . self::BALANCE_API)->jsonToArray();
        if ($body) {
            return intval($body['sumSms'] ?? 0);
        }
        return 0;
    }

    /**
     * @describe 发送模板短信
     * @doc https://doc.zthysms.com/web/?#/1/13
     * @user zlf <zms-pro@qq.com> 2025/3/19
     * @param string $phone
     * @param string $template_key
     * @param array $data
     * @return SmsResult
     * @throws \Exception
     */
    public function send(string $phone, string $template_key, array $data = []): SmsResult
    {
        $conf = $this->getConfig();
        $tKey = time();
        $content = $this->renderContent($conf->template, $template_key, array_merge($data, ['signature' => $conf->signature]));
        $postData = [
            'username' => $conf->username,
            'password' => md5(md5($conf->password) . $tKey),
            'tKey' => $tKey,
            'signature' => "【{$conf->signature}】",
            'tpId' => $this->getTemplateCode($template_key, $conf->template),
            'records' => [
                [
                    'mobile' => $phone,
                    'tpContent' => $data
                ]
            ]
        ];
        $request = Http::instance()
            ->setMethod('POST')
            ->setData(Json::encode($postData))
            ->setHeader('Content-Type', 'application/json; charset=utf-8')
            ->execute($conf->host . self::SEND_SMS_TMP_API)
            ->jsonToArray();
        if ($request) {
            if (isset($request['msg']) && $request['msg'] === 'success') {
                return new SmsResult(['phone' => $phone, 'content' => $content, 'status' => true, 'driver' => static::class, 'template_key' => $template_key, 'request' => $request]);
            }
        }
        return new SmsResult(['phone' => $phone, 'content' => $content, 'status' => false, 'driver' => static::class, 'template_key' => $template_key, 'request' => $request]);
    }


    /**
     * @describe 发送任意短信
     * @doc https://doc.zthysms.com/web/?#/1/14
     * @user zlf <zms-pro@qq.com> 2025/3/19
     * @param string $phone
     * @param string $template_key
     * @param array $data
     * @return SmsResult
     * @throws \Exception
     */
    public function sendBody(string $phone, string $content, array $data = []): SmsResult
    {
        $conf = $this->getConfig();
        $tKey = time();
        $content = Str::render($content, $data);
        $postData = [
            'username' => $conf->username,
            'password' => md5(md5($conf->password) . $tKey),
            'tKey' => $tKey,
            'mobile' => $phone,
            'content' => $content
        ];
        $request = Http::instance()
            ->setMethod('POST')
            ->setData(Json::encode($postData))
            ->setHeader('Content-Type', 'application/json; charset=utf-8')
            ->execute($conf->host . self::SEND_SMS_API)
            ->jsonToArray();
        if ($request) {
            if (isset($request['msg']) && $request['msg'] === 'success') {
                return new SmsResult(['phone' => $phone, 'content' => $content, 'status' => true, 'driver' => static::class, 'template_key' => '', 'request' => $request]);
            }
        }
        return new SmsResult(['phone' => $phone, 'content' => $content, 'status' => false, 'driver' => static::class, 'template_key' => '', 'request' => $request]);
    }


    /**
     * 获取模板ID
     * @param string $template_key
     * @param array $template
     * @return string
     */
    private function getTemplateCode(string $template_key, array $template): string
    {
        foreach ($template as $item) {
            if ($item['KEY'] === $template_key) {
                return $item['TEMPLATE_ID'];
            }
        }
        return '';
    }
}